# -*- coding:utf-8 -*-
# 检测 服务器上 是否有安装 ipas 包 和 安装包 下载帐号是否存在
import ctypes
import threading
import MySQLdb
import os
import socket
import json
import httplib
import urllib2
import uuid
import zipfile
import base64
import sys
import hashlib
import datetime
import time
import subprocess
import xml.dom.minidom
from biplist import *

db_host   = "192.168.11.6"
db_user   = 'xyzs'
db_passwd = 'ikF5NNeJg2G8'
db_port   = 3309
db_name   = "app_xyapplist"

def commom_log(filename, content , write_type='wb'):
    try:
        f = open(filename , write_type)
        f.write(content);
        f.close()
    except:
        print('happen an exception when write file')
        return ""

def getInfoPlist(random_filename):
    try:
        zf       = zipfile.ZipFile(random_filename, "r")
        nList    = zf.namelist()
        type_val = 0
        BundleId = ''
        CFBundleShortVersionString = ''
        CFBundleVersion = ''
        for f in nList:
            if f.rfind('Info.plist') != -1:
                f_arr = f.split("/")
                if len(f_arr) == 3:
                    if(f_arr[2] == 'Info.plist'):
                        info     = zf.read(f)
                        plist    = readPlistFromString(info)
                        BundleId = plist['CFBundleIdentifier']

                        if plist.has_key('CFBundleShortVersionString'):
                            CFBundleShortVersionString = plist['CFBundleShortVersionString']
                        else:
                            CFBundleShortVersionString = ''
                        if plist.has_key('CFBundleVersion'):
                            CFBundleVersion = plist['CFBundleVersion']
                        else:
                            CFBundleVersion = ''

                        print CFBundleVersion

        return BundleId,CFBundleShortVersionString,CFBundleVersion
    except:
        return '','',''


def get_version(random_filename):
    try:
        zf = zipfile.ZipFile(random_filename, "a")
        zf.getinfo("iTunesMetadata.plist")
        data = zf.read("iTunesMetadata.plist")
        if data :

            index   = data.rfind('account hash')
            if index != -1:
                index_right = data.find('</string>', index)
                account_hash = data[index: index_right]
                account_hash = account_hash.replace("account hash</key>" , '').replace("<string>", "").strip()
            else:
                account_hash = ''

            index   = data.rfind('bundleShortVersionString')
            if index != -1:
                index_right = data.find('</string>', index)
                version = data[index: index_right]
                version = version.replace("bundleShortVersionString</key>" , '').replace("<string>", "").strip()
            else:
                version = ''
            index   = data.rfind('bundleVersion')
            if index != -1:
                index_right = data.find('</string>', index)
                bundleVersion = data[index: index_right]
                bundleVersion = bundleVersion.replace("bundleVersion</key>" , '').replace("<string>", "").strip()
            else:
                bundleVersion = ''
            return  version,bundleVersion,account_hash
        else:
            return '','',''
    except:
        return '','',''

arr  = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f'
arr  = arr.split(",")
conn = MySQLdb.connect(host=db_host,user=db_user,passwd=db_passwd,port=db_port,init_command="set names utf8")
conn.select_db(db_name)
cur  = conn.cursor()
for x in arr:
    for xx in arr :
        tb_name = 'app_xyapplist_'+str(x)+".t_xyapplist_"+x+xx
        sql     = "select itunesid,is_install,is_j_install  from "+tb_name + " where is_install = 1 and is_hot = 0";
        print sql
        cur.execute(sql)
        result = cur.fetchall()
        for f in result:
            itunesid      = f[0]
            is_install    = f[1]
            is_j_install  = f[2]

            print "start : "+str(itunesid)

            m = hashlib.md5(str(itunesid))
            m.digest()
            md5  = m.hexdigest()
            str1 = md5[0: 2]
            str2 = md5[2: 4]

            random_filename = '/data/app/ipas/'+ str(str1) + "/" + str(str2) + "/" + str(md5) + str(str2) + str(str1) + '.ipa'
            jailbreak_file  = '/data/app/jailbreak/'+ str(str1) + "/" + str(str2) + "/" + str(itunesid) + '.ipa'

            print random_filename
            print jailbreak_file

            if os.path.exists(random_filename):

                z_InfoPlist   = get_version(random_filename)
                if z_InfoPlist[0]:
                    if is_j_install == 0: 
                        # 没有越狱包 ，需要破解
                        print random_filename + "--->>no ipas\n"
                        commom_log('download_meta_log' , random_filename+"\n" , 'a')
                    else:
                        j_InfoPlist = get_version(jailbreak_file)
                        if j_InfoPlist[0]:
                            if z_InfoPlist[1] == j_InfoPlist[1] and z_InfoPlist[2] == j_InfoPlist[2]:
                                print str(itunesid) + " : don't jailbreak \n"
                            else:
                                print random_filename + "--->>has ipas , version don't same\n"
                                commom_log('download_meta_log' , random_filename+"\n" , 'a')    
                        else:
                            print random_filename + "--->>has ipas ,jailbreak parse faile\n"
                            commom_log('download_meta_log' , random_filename+"\n" , 'a')
                            #越狱包解析失败，需要破解


                # z_InfoPlist = getInfoPlist(random_filename)
                # if z_InfoPlist[0]:
                #     if is_j_install == 0: 
                #         # 没有越狱包 ，需要破解
                #         print random_filename + "--->>no ipas\n"
                #         commom_log('download_log' , random_filename+"\n" , 'a')
                #     else:
                #         j_InfoPlist = getInfoPlist(jailbreak_file)
                #         if j_InfoPlist[0]:
                #             if z_InfoPlist[1] == j_InfoPlist[1] and z_InfoPlist[2] == j_InfoPlist[2]:
                #                 print str(itunesid) + " : don't jailbreak \n"
                #             else:
                #                 print random_filename + "--->>has ipas , version don't same\n"
                #                 commom_log('download_log' , random_filename+"\n" , 'a')    
                #         else:
                #             print random_filename + "--->>has ipas ,jailbreak parse faile\n"
                #             commom_log('download_log' , random_filename+"\n" , 'a')
                #             #越狱包解析失败，需要破解
                # else:
                #     str(itunesid) + "zhengban ipas parse error\n"
                #     sql_sum = "update app_xyapplist.t_xyappsum set is_install = 0 where itunesid = '"+str(itunesid)+"';";
                #     sql_app = "update "+tb_name+" set is_install = 0 where itunesid = '"+str(itunesid)+"';";
                #     commom_log('sql_sum_error.log' , sql_sum + "\n" , 'a')
                #     commom_log('sql_app_error.log' , sql_sum + "\n" , 'a')
            else:
                str(itunesid) + "no zhengban ipas\n"
                sql_sum = "update app_xyapplist.t_xyappsum set is_install = 0 where itunesid = '"+str(itunesid)+"';";
                sql_app = "update "+tb_name+" set is_install = 0 where itunesid = '"+str(itunesid)+"';";
                commom_log('sql_sum_error.log' , sql_sum + "\n" , 'a')
                commom_log('sql_app_error.log' , sql_sum + "\n" , 'a')
cur.close()
conn.close()